import http from '@/utils/http'
import type { PageQuery, PageRes } from '@/types/api'
import type { UploadFile } from 'element-plus'

const BASE_URL = 'template/testReport'

// ==================== 类型定义 ====================

// 测试信息
export interface TaskInfo {
  id: number
  taskName: string
  description: string
  startTime: string
  endTime: string
}
//项目信息
export interface ProjectInfo {
  id: number
  projectName: string
}
//设备信息
export interface DeviceInfo {
  deviceName: string
  location: string
}
export interface UserDuty {
  nickName: string[]
  handler: Record<string, any>
}
export interface UserParticipant {
  nickName: string[]
  handler: Record<string, any>
}
export interface TaskTestTemplate {
  templateId: number
  taskTemplateUrl:string
}
export interface TaskTemplateSearchResp {
  taskInfo: TaskInfo
  projectInfo: ProjectInfo
  deviceInfo: DeviceInfo[]
  userDuty: UserDuty
  userParticipant: UserParticipant
  taskTestTemplate: TaskTestTemplate
}
export interface ReportDataModel {
  projectId: string
  taskInfo: TaskInfo
  projectInfo: ProjectInfo
  deviceInfo: DeviceInfo[]
  userDuty: UserDuty
  userParticipant: UserParticipant
  taskTestTemplate: TaskTestTemplate
  conclusion: string
  sensors: Sensor[]
  fileName?: string
  dataTemplateName?:string
  remark?:string
  firstPicture?: UploadFile  
  secondPicture?: UploadFile  
  formulas: FormulaItem[]
  taskSource: {
    fileName: string
    fileNumber: string
  }
  experiment: {
    process: string
    systemName: string
    maxSampleRate: string
    sampleDetails: string
  }
  experimentRecord: {
    fileNumber: string
    archiveNumber: string
  }
  sensorTableName: string
  statisticalTableName: string
  appendixTableName: string
  /** 统计表数据（二维数组，第一行为表头，后续行为数据） */
  statisticalTableData: string[][]
  /** 附录表1数据（二维数组，第一行为表头，后续行为数据） */
  appendix1TableData: string[][]
  /** 附录表2数据（二维数组，第一行为表头，后续行为数据） */
  appendix2TableData: string[][]
  /** 附录表1标题（用于在合并表格中区分数据） */
  appendix1Title?: string
  /** 附录表2标题（用于在合并表格中区分数据） */
  appendix2Title?: string
}

export interface FormulasFileUrls{
  fileUrl:string
  pictureIndex:string
}

export interface Result<T = any> {
  code: number;
  message: string;  
  data: T;
  success: boolean; 
  timestamp: number;
}

export interface FileUser{
  nickname:string;
}

// 设备信息
export interface CopyDeviceStoreDO {
  location:string
}

// 测量参数
export interface Sensor {
  index:number
  parameterName: string
  symbol: string
  unit: string
  measureRange: string
  accuracy: string
  location: string
  measurementPoint:string
}
//公式参数
export interface FormulaItem {
  formulaIndex: number
  fileUrls: FormulasFileUrls[] 
  description: string
  valueExplanation: string
}
export interface Param {
  index:number
  param1: string
  param2: string
  param3: string
  param4: string
  param5: string
}
export interface ParamHeaders {
  param1: string
  param2: string
  param3: string
  param4: string
  param5: string
}

export interface TaskOption {
  id: number
  name: string
}

export interface TaskFileDataTemplateResp {
  id: number
  taskName: string
  templateName: string
  dataTemplateName: string
  remark: string
  createUserName: string
}

export interface TaskFileDataTemplatePageQuery {
  taskName?: number
  dataTemplateName?: string
  page?: number
  size?: number
}
export interface FileUploadResponse {
  url: string
}

export interface TemplatePlaceholder {
  key: string
  label: string
  type: string
  description: string
}

export interface TestTemplateResp {
  id: number
  name: string
  version?: number
  filePath: string
  remark?: string
  createTime?: string
  placeholderKeys: string[]
  placeholders: TemplatePlaceholder[]
}

export interface TestTemplateReq {
  name: string
  version?: number
  filePath: string
  remark?: string
  placeholderKeys: string[]
}

export interface TestTemplateQuery {
  page: number
  size: number
  name?: string
  version?: number
}

// ==================== API 方法 ====================

/** 生成测试报告 */
export function generateTestReport(data: ReportDataModel) {
  return http.postDownload(`${BASE_URL}/generate`, data);
}
/** 保存报告草稿 */
export function saveReportDraft(data: ReportDataModel) {
  return http.post<Result<string>>(`${BASE_URL}/draft`, data)
}

/** 获取报告草稿 */
export function getReportDraft(draftId: string) {
  return http.get<Result<ReportDataModel>>(`${BASE_URL}/draft/${draftId}`)
}

/** 搜索任务 */
export const searchTasks = async (query?: string): Promise<TaskOption[]> => {
  try {
    const res = await http.get<Result<TaskOption[]>>('/task/info/searchAny', {
      params: { keyword: query }
    })
    return res.data?.data || []
  } catch (error) {
    console.error('搜索任务失败:', error)
    return []
  }
}

/** 返回要填充的具体信息 */
export const searchTaskTemplateInformation = (id: number) => {
  return http.post<Result<TaskTemplateSearchResp>>(`/task/info/searchTaskTemplateInformation/${id}`)
}

/** 查询具体数据模板信息 */
export function selectDataTemplates(query: TaskFileDataTemplatePageQuery) {
  return http.post<PageRes<TaskFileDataTemplateResp>>(`${BASE_URL}/select`, query)
}

/** 删除对应数据模板 */
export function deleteDataTemplate(ids: number[]) {
  return http.del(`${BASE_URL}/delete`, ids) // 直接发送数组
}

const TEMPLATE_BASE_URL = 'template/testTemplate'

/** 获取模板占位符列表 */
export function listTemplatePlaceholders() {
  return http.get<TemplatePlaceholder[]>(`${TEMPLATE_BASE_URL}/placeholders`)
}

/** 查询测试模板列表 */
export function listTestTemplates(query: TestTemplateQuery) {
  return http.get<PageRes<TestTemplateResp[]>>(`${TEMPLATE_BASE_URL}`, query)
}

/** 新增测试模板 */
export function createTestTemplate(data: TestTemplateReq) {
  return http.post(`${TEMPLATE_BASE_URL}`, data)
}

/** 更新测试模板 */
export function updateTestTemplate(id: number, data: TestTemplateReq) {
  return http.put(`${TEMPLATE_BASE_URL}/${id}`, data)
}

/** 删除测试模板 */
export function deleteTestTemplate(id: number) {
  return http.del(`${TEMPLATE_BASE_URL}/${id}`)
}

/** 下载测试模板 */
export function downloadTestTemplate(id: number) {
  return http.download(`${TEMPLATE_BASE_URL}/${id}/download`)
}